import Vue from 'vue'
import axios from 'axios'
import global from '../constant/Global'

let GLOBAL = global

// 每次请求携带sessionid，不配置此项后台无法获取登录信息
axios.defaults.withCredentials = true

axios.interceptors.request.use(config => {
  if (localStorage.getItem(GLOBAL.localStoreKey.token)) {
    config.headers.Authorization = localStorage.getItem(GLOBAL.localStoreKey.token)
  }
  return config
}, error => {
  return Promise.reject(error)
})

// 响应拦截
axios.interceptors.response.use(function (response) {
  // 是否登录异常
  if (response.data.code === 4003 || // token为空
    response.data.code === 4004) { // token错误
    console.log('登录信息已超时，请重新登录, code: ' + response.data.code)
    localStorage.removeItem(GLOBAL.localStoreKey.token)
    Vue.$router.push('/login')
  }

  // 如果返回头里传入了新的token，则需要刷新
  if (response.headers.authorization !== undefined) {
    localStorage.setItem(GLOBAL.localStoreKey.token, response.headers.authorization)
  }

  return response
}, function (error) {
  return Promise.reject(error)
})

export default axios
